package com.icez.bwebviewlibrary

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.net.http.SslError
import android.os.Build
import android.util.AttributeSet
import android.util.Log
import android.view.ViewGroup
import android.webkit.*
import androidx.annotation.RequiresApi
import androidx.lifecycle.*
import com.icez.bwebviewlibrary.bridge.JsBridgeInterface
import com.icez.bwebviewlibrary.enum.BWebViewLoadType
import com.icez.bwebviewlibrary.lpi.BWebViewInterface

/**
 *
 * // 文件访问权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
 * @sample 通用webview
 */
class BWebView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : WebView(context, attrs), BWebViewInterface,DefaultLifecycleObserver {

    private var isInitListenered = false
    private var mBWebViewLoadType: BWebViewLoadType? = null

    init {
        //支持js
        settings.javaScriptEnabled = true
        //暂时不加载图片
        settings.loadsImagesAutomatically = false
        //内容安全站点模式,启用允许任何来源内容，即使不安全的内容
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
        //允许从网络加载图片
        settings.blockNetworkImage = false
        //允许访问文件
        settings.allowFileAccess = true
        //允许访问本地资源
        settings.allowContentAccess = true
        //启用dom storage
        settings.domStorageEnabled = true
    }

    companion object {
        // 加載本地assets文件下面的文件
        open val ANDROID_ASSET_INDEX = "file:///android_asset/"
    }

    override fun loadWeb(
        url: String,
        onPageStartedListenner: (() -> Unit)?,
        onPageFinishedListenner: (() -> Unit)?,
        onPageErrorListenner: ((errorResponse: WebResourceResponse?,error: WebResourceError?) -> Unit)?,
        onProgressChangedListener: ((newProgress: Int) -> Unit)?,
        onReceivedIconListener: ((icon: Bitmap?) -> Unit)?,
        onReceivedTitleListener: ((title: String?) -> Unit)?
    ) {
        if (url.indexOf("http") == 0 || url.indexOf("https") == 0) {
            mBWebViewLoadType = BWebViewLoadType.HTTP
        } else if (url.indexOf(ANDROID_ASSET_INDEX) == 0) {
            mBWebViewLoadType = BWebViewLoadType.ASSETS
        }
        post {
            loadUrl(url)
        }

        setListener(
            onPageStartedListenner,
            onPageFinishedListenner,
            onPageErrorListenner,
            onProgressChangedListener,
            onReceivedIconListener,
            onReceivedTitleListener
        )
    }

    private fun setListener(
        onPageStartedListenner: (() -> Unit)?,
        onPageFinishedListenner: (() -> Unit)?,
        onPageErrorListenner: ((errorResponse: WebResourceResponse?,error: WebResourceError?) -> Unit)?,
        onProgressChangedListener: ((newProgress: Int) -> Unit)?,
        onReceivedIconListener: ((icon: Bitmap?) -> Unit)?,
        onReceivedTitleListener: ((title: String?) -> Unit)?
    ) {
        if (!isInitListenered) {
            webListenter(
                onPageStartedListenner,
                onPageFinishedListenner,
                onPageErrorListenner,
                onProgressChangedListener,
                onReceivedIconListener,
                onReceivedTitleListener
            )
            isInitListenered = true
        }
    }

    override fun loadDataWeb(
        htmlData: String, mimeType: String?, encoding: String?,
        onPageStartedListenner: (() -> Unit)?,
        onPageFinishedListenner: (() -> Unit)?,
        onPageErrorListenner: ((errorResponse: WebResourceResponse?,error: WebResourceError?) -> Unit)?,
        onProgressChangedListener: ((newProgress: Int) -> Unit)?,
        onReceivedIconListener: ((icon: Bitmap?) -> Unit)?,
        onReceivedTitleListener: ((title: String?) -> Unit)?
    ) {
        post {
            loadData(htmlData, mimeType, encoding)
        }

        setListener(
            onPageStartedListenner,
            onPageFinishedListenner,
            onPageErrorListenner,
            onProgressChangedListener,
            onReceivedIconListener,
            onReceivedTitleListener
        )
    }

    override fun toJsMethod(jsMethodName: String, jsMethodParams: ArrayList<String>?) {
        var params: String = ""
        val jsMethodParamsSize = jsMethodParams?.size ?: 0
        jsMethodParams?.forEachIndexed { index, s ->
            if (index != (jsMethodParamsSize - 1)) {
                params += s
            } else {
                params += s + ","
            }
        }
        post {
            if(jsMethodParams.isNullOrEmpty()){
                loadUrl("javascript:" + jsMethodName + "()")
            }else{
                loadUrl("javascript:" + jsMethodName + "(" + params + ")")
            }
        }


    }


    @SuppressLint("JavascriptInterface")
    override fun setJsBridge(mJsBridgeInterface: JsBridgeInterface, name: String) {
        addJavascriptInterface(mJsBridgeInterface, name)
    }

    private fun webListenter(
        onPageStartedListenner: (() -> Unit)?,
        onPageFinishedListenner: (() -> Unit)?,
        onPageErrorListenner: ((errorResponse: WebResourceResponse?,error: WebResourceError?) -> Unit)?,
        onProgressChangedListener: ((newProgress: Int) -> Unit)?,
        onReceivedIconListener: ((icon: Bitmap?) -> Unit)?,
        onReceivedTitleListener: ((title: String?) -> Unit)?
    ) {
        webViewClient = object : WebViewClient() {
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                Log.e("icez","onPageFinished")
                if(!settings.loadsImagesAutomatically){
                    settings.loadsImagesAutomatically = true
                }
                if (onPageFinishedListenner != null) {
                    onPageFinishedListenner()
                }
            }

            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                Log.e("icez","onPageStarted")
                if (onPageStartedListenner != null) {
                    onPageStartedListenner()
                }
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
                if (onPageErrorListenner != null && (request?.url?:"") == (view?.url?:"")) {
                    Log.e("icez","onPageErrorListenner")
                    onPageErrorListenner(null,error)
                }
            }

            override fun onReceivedHttpError(
                view: WebView?,
                request: WebResourceRequest?,
                errorResponse: WebResourceResponse?
            ) {
                super.onReceivedHttpError(view, request, errorResponse)
                Log.e("icez","onReceivedHttpError"+errorResponse)
//                if (onPageErrorListenner != null) {
//                    onPageErrorListenner(errorResponse,null)
//                }
            }

            override fun onReceivedSslError(
                view: WebView?,
                handler: SslErrorHandler?,
                error: SslError?
            ) {
                super.onReceivedSslError(view, handler, error)
                //忽略该证书错误
                handler?.proceed()
            }



        }
        webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                super.onProgressChanged(view, newProgress)
                Log.e("icez","onProgressChanged"+newProgress)
                if (onProgressChangedListener != null) {
                    onProgressChangedListener(newProgress)
                }
            }

            override fun onReceivedIcon(view: WebView?, icon: Bitmap?) {
                super.onReceivedIcon(view, icon)
                Log.e("icez","onReceivedIcon")
                if (onReceivedIconListener != null) {
                    onReceivedIconListener(icon)
                }
            }

            override fun onReceivedTitle(view: WebView?, title: String?) {
                super.onReceivedTitle(view, title)
                Log.e("icez","onReceivedTitle")
                if (onReceivedTitleListener != null) {
                    onReceivedTitleListener(title)
                }
            }


        }
    }


    override fun onResume(owner: LifecycleOwner) {
        super<DefaultLifecycleObserver>.onResume(owner)
        Log.e("icez","onResume")

    }

    override fun onDestroy(owner: LifecycleOwner) {
        Log.e("icez","销毁")
        this.removeAllViews()
        this.destroy()
        if(parent!=null && parent is ViewGroup){
            (parent as ViewGroup).removeView(this)
        }
        super.onDestroy(owner)
    }
}